<template>
  <div class="bg">
   <div id="login">
      <h2 >拾文博客</h2>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="20%">
        <el-form-item label="账  号:" prop="username">
          <el-input placeholder="请输入账号" v-model="ruleForm.username" show-word-limit clearable/>
        </el-form-item>
        <el-form-item  label="密  码:" prop="password" >
          <el-input placeholder="请输入密码" v-model="ruleForm.password" show-password clearable />
        </el-form-item>
        <el-form-item label="验证码:" prop="password" >
          <el-input placeholder="看不清？点击图片换一张" v-model="ruleForm.code" clearable style="width: 175px;float: left"/>
          <a href="javascript:void(0)" @click="getVerificationCode()">
            <img :src="verificationJng" alt="图片无法显示" style="width: 100px;float: right">
          </a>
        </el-form-item>
        <el-form-item>
          <span class="reg">
            <a href="javascript:void(0)" @click="automaticVerification">自动验证 | </a>
            <a href="javascript:void(0)" @click="sms">手机登录 | </a>
            <a href="javascript:void(0)" @click="forgotPassword">忘记密码 | </a>
            <a href="javascript:void(0)" @click="userRegister">前往注册</a>
          </span>
        </el-form-item>
        <el-form-item>
          <el-button  type="primary" round @click="submitForm('ruleForm')" class="btn">登录</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--引入粒子特效-->
    <vue-particles
        color="#fff"
        :particleOpacity="0.7"
        :particlesNumber="60"
        shapeType="circle"
        :particleSize="4"
        linesColor="#fff"
        :linesWidth="1"
        :lineLinked="true"
        :lineOpacity="0.4"
        :linesDistance="150"
        :moveSpeed="2"
        :hoverEffect="true"
        hoverMode="grab"
        :clickEffect="true"
        clickMode="push"
        class="lizi"
    >
    </vue-particles>

  </div>
</template>

<script>
export default {
  data() {
    return {
      // 登录信息记录
      invalidClick:{
        invalidCount:0,
        invalidName: '1',
        invalidPassword: '1',
      },
      // 用户实例
      ruleForm: {
        username: 'admin',
        password: '123456',
        code:'',
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'blur'},
        ],
      },
      verificationCode:'',
      verificationJng:'',
    };
  },
  methods: {
    submitForm(formName) {
      /**
       * 空数据登录拦截
       */
      if (this.invalidClick.invalidName == this.ruleForm.username && this.invalidClick.invalidPassword == this.ruleForm.password) {
        if (this.invalidClick.invalidCount === 0){
          this.$message({
            type:"info",
            message:'请不要重复提交无效请求',
          })
          this.invalidClick.invalidCount = 1;
          setTimeout(()=>{
            this.invalidClick.invalidCount = 0;
          },1500)
          return;
        }
        if (this.invalidClick.invalidCount === 10){
          this.$message({
            type:"info",
            message:'请不要重复提交无效请求'
          })
          this.invalidClick.invalidCount = 1;
          return;
        }
        this.invalidClick.invalidCount += 1;
        return;
      }

      if (localStorage.getItem("jwt")!=null){
        localStorage.clear();
      }

      if (this.verificationCode != this.ruleForm.code){
        this.$message({
          type: 'error',
          message: "验证码错误"
        })
        this.ruleForm.code = "";
        return;
      }

      this.$refs[formName].validate((valid) => {
        let then = this;
        if (valid) {
          let path = "http://localhost:9090/system/users/login";
          console.log('url >>> ' + path)
          let data = {
            username: this.ruleForm.username,
            password: this.ruleForm.password,
          }

          console.log("用户登录信息：【用户名："+data.username+"，密码："+data.password+"】")
          this.axios.post(path,data).then((response) => {
            switch (response.data.code) {
              case 200:
                let jwt = response.data.data;
                // console.log("登录成功：获得令牌："+ jwt);
                localStorage.setItem('jwt',jwt);
                then.$message({
                  type: 'success',
                  message: "登录成功"
                });
                then.init();
                then.$router.push('/');
                setTimeout(()=>{
                  then.loginWebsocket();
                  //延迟时间：0.8秒
                },500)
                break;
              default:
                then.invalidClick.invalidName = then.ruleForm.username;
                then.invalidClick.invalidPassword = then.ruleForm.password;
                then.$message({
                  type: 'error',
                  message: response.data.message
                })
                break;
            }
          }).catch((response)=>{
            then.$message({
              type: 'info',
              message: "网络异常，操作失败！"
            })
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    getVerificationCode(){
      this.axios.get('http://localhost:9090/captcha', {responseType: 'blob'}).then((response) => {
        this.verificationJng = window.URL.createObjectURL(response.data); // 获取图形验证码图片
        this.verificationCode = response.headers.captcha; // 获取验证码
        console.log("图形验证码："+this.verificationCode)
      })

    },

    // 为了方便开发，启用自动验证功能
    automaticVerification(){
      this.ruleForm.code = this.verificationCode;
    },

    // 短信验证登录
    sms(){
      this.$router.push({
        path:'/Verification',
        query: {
          id: 1
        }
      })
    },

    // 忘记密码
    forgotPassword(){
      this.$router.push({
        path:'/Verification',
        query: {
          id: 2
        }
      })
    },

    // 注册
    userRegister(){
      this.$router.push("/RegisterView")
    },

    init: function () {
      console.log("实例化websocket")
      if (typeof (WebSocket) === "undefined") {
        console.log("您的浏览器不支持socket")
      } else {
        // 实例化socket
        //userId是你要发送的用户id
        this.socket = new WebSocket("ws://localhost:9090/webSocketToUser/" + 2)
        // 监听socket连接
        this.socket.onopen = this.open
        // 监听socket错误信息
        this.socket.onerror = this.error
        // 监听socket消息
        this.socket.onmessage = this.getMessage
      }
    },
    open: function () {
      console.log("socket连接成功")
    },
    error: function () {
      console.log("连接错误")
    },
    getMessage: function (msg) {
      this.openMsg(msg.data)
    },
    send: function () {
      this.socket.send(params)
    },
    close: function () {
      console.log("socket已经关闭")
    },
    openMsg(msg) {
      let _self = this;
      this.$notify({
        title: '提示',
        message: msg,
        duration: 0,
        type: 'warning',
        onClose: function () {
        }
      })
    },
    loginWebsocket(){
      this.axios.get("http://localhost:9090/system/users/loginWebSocket")
    }
  },
  created() {
    this.getVerificationCode();
  }
}
</script>


<style scoped>
.bg {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  /*background: url('https://ts1.cn.mm.bing.net/th/id/R-C.51676491f69a1c1b3b043035c7565760?rik=ahRHaUMH3E02lg&riu=http%3a%2f%2fwww.kuaipng.com%2fUploads%2fpic%2fb%2f2019%2f09-13%2f69781%2fbeijing_pic_69781_1200_600.jpg&ehk=F9XpXpcQR%2f3zuIkcEWrvMl8myfV4bm%2fwfw4lDwMbVy8%3d&risl=&pid=ImgRaw&r=0');*/
  /*background-size: 100% 100%;*/
  background-color: #2d3a4b;
}
body{
  -moz-user-select: none;
}

#login {
  height: 400px;
  width: 430px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.25);
  background:#ffffff;
  opacity: 0.85;
  position: absolute;
  top: 20%;
  left: 35%;
  text-align: center;
  display: flex;
  flex-direction: column; /*横向*/
  padding: 30px;
  border-radius: 15px;
}

#login h2 {
  padding-bottom: 30px;
}

.btn {
  width: 80%;
  margin: auto;

}

.reg {
  float: right;
  height: 10px;
  line-height: 20px;
  position: relative;
  top: -10px;
}
a{
  color: #908f8f;
  text-decoration:none;
}
</style>

